// pages/group-head/month-order.js
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() + 1
const nowDay = date.getDate()
const app = getApp()
const pool = new Map()
const tabs = [{
        name: "待配送",
        status: 20
    },
    {
        name: "已发货",
        status: 21
    },
    {
        name: "待自提",
        status: 11
    },
    {
        name: "已完成",
        status: 40
    },
]

const orderActions = [{
        name: "查看详情",
        method: "toDetail",
        type: 1
    },
    {
        name: "确认到货",
        method: "doOrder",
        type: 2
    },
    {
        name: "扫码提货",
        method: "scanCode",
        type: 3
    },
    {
        name: "取件码提货",
        method: "showPutCode",
        type: 3
    },
]

function findAction() {
    return orderActions.filter(o => {
        return Array.from(arguments).indexOf(o.name) >= 0
    })
}

function getOrderAction(item) {
    const status = parseInt(item.status)
    let r = []
    switch (status) {
        case 20:
            r = findAction("查看详情")
            break
        case 21:
            r = findAction("确认到货")
            break
        case 11:
            r = findAction("扫码提货", "取件码提货")
            break
        case 40:
            break
    }
    return r
}


let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
// 根据年月 获取当月的总天数
let getDays = function(year, month) {
    if (month === 2) {
        return ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28
    } else {
        return daysInMonth[month - 1]
    }
}
// 根据年月日设置当前月有多少天 并更新年月日数组
let setDate = function(year, month, day, _th) {
    let daysNum = year === nowYear && month === nowMonth ? nowDay : getDays(year, month)
    day = day > daysNum ? 1 : day
    let monthsNum = year === nowYear ? nowMonth : 12
    let years = []
    let months = []
    let days = []
    let yearIdx = 9999
    let monthIdx = 0
    let dayIdx = 0

    // 重新设置年份列表
    for (let i = 2010; i <= nowYear; i++) {
        years.push(i)
    }
    years.map((v, idx) => {
        if (v === year) {
            yearIdx = idx
        }
    })
    // 重新设置月份列表
    for (let i = 1; i <= monthsNum; i++) {
        months.push(i)
    }
    months.map((v, idx) => {
        if (v === month) {
            monthIdx = idx
        }
    })
    // 重新设置日期列表
    for (let i = 1; i <= daysNum; i++) {
        days.push(i)
    }
    days.map((v, idx) => {
        if (v === day) {
            dayIdx = idx
        }
    })

    console.log(day, 'setData')
    _th.setData({
        years: years, //年份列表
        months: months, //月份列表
        days: days, //日期列表
        value: [yearIdx, monthIdx, dayIdx],
        year: year,
        month: month,
        day: day
    })
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        years: [],
        months: [],
        days: [],
        year: nowYear,
        month: nowMonth,
        day: nowDay,
        value: [9999, 1, 1],
        status: 20,
        showInput: false,
        showPutCode: false,
        showFilter: false,
        current_village: null,
        mobile_search: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let statusObj = {}
        app.community()
        Object.keys(tabs).forEach(k => {
            statusObj[tabs[k].status] = tabs[k].name
        })
        this.setData({
            statusObj,
            tabs,
        })
        setDate(this.data.year, this.data.month, this.data.day, this)
        this.loadData()
    },
    loadData() {
        let tab = pool.get(this.data.status)
        if (!tab) {
            tab = {
                page: 1,
                nextPage: true,
                list: []
            }
            pool.set(this.data.status, tab)
        }
        this.setData(tab)
        if (!tab.nextPage) {
            this.setData(tab)
            return
        }

        if (tab.page == 1) {
            wx.showLoading({
                title: '加载中...',
            })
        }

        if (this.data.loading) {
            return
        }

        this.setData({
            loading: true
        })

        app.http.post("administrator/order-list?page=" + tab.page, {
            data: {
                status: this.data.status,
                y: this.data.year,
                m: this.data.month,
                d: this.data.day,
                type: 2,
                mobile: this.data.mobile_search ? this.data.mobile_search : null,
                community_id: this.data.current_village ? this.data.current_village : null
            }
        }).then(res => {
            tab.list.push(...res.data.list.map(o => {
                o.actions = getOrderAction(o)
                return o
            }))
            tab.page++
                tab.nextPage = res.data.pageStatus
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
            this.setData({
                loading: false
            })
        }).catch(err => {
            app.wxToast.error(err.message)
            this.setData({
                loading: false
            })
        })
    },
    showInput() {
        this.setData({
            showInput: !this.data.showInput
        })
    },
    clickTab(evt) {
        const status = evt.currentTarget.dataset.status
        if (status != this.data.status) {
            this.setData({
                status
            })
            let tab = pool.get(this.data.status)
            if (tab && tab.list.length == 0) {
                tab.page = 1
                tab.nextPage = true
            }
            this.loadData()
        }
    },
    //详情
    toDetail(evt) {
        let {
            submittype,
            orderid
        } = evt.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/group-head/order-detail?order_id=' + orderid,
        })
    },
    //操作按钮
    doOrder(evt) {
        let {
            submittype,
            orderid
        } = evt.currentTarget.dataset
        wx.showLoading({
            title: '请稍等...',
        })
        let data = {
            order_id: orderid,
            type: submittype
        }
        if (this.data.take_code) {
            this.setData({
                showPutCode: false
            })
            data.take_code = this.data.take_code
        }
        app.http.get('administrator/status', {
            data
        }).then(res => {
            console.log(res, 'xxxx')
            wx.hideLoading()
            if (res.data.status == 1) {
                wx.showToast({
                    icon: 'none',
                    title: '操作成功',
                })
                this.onPullDownRefresh()
            } else {
                wx.showModal({
                    title: '小提示',
                    content: res.data.msg,
                    showCancel: false,
                    confirmColor: '#ff5400'
                })
            }
        }).catch(err => {
            console.log(err, 'errxxxxxxxx')
            wx.hideLoading()
        })

    },
    //扫二维码
    scanCode(evt) {
        let {
            submittype,
            orderid
        } = evt.currentTarget.dataset
        wx.scanCode({
            success: res => {
                this.setData({
                    take_code: res.result,
                })
                this.doOrder({
                    currentTarget: {
                        dataset: {
                            submittype,
                            orderid
                        }
                    }
                })
            }
        })
    },
    //弹出取件码输入框
    showPutCode(evt) {
        let {
            submittype,
            orderid
        } = evt.currentTarget.dataset
        let obj = {
            showPutCode: !this.data.showPutCode,
        }
        if (submittype && orderid) {
            obj.submittype = submittype
            obj.orderid = orderid
        }
        this.setData(obj)
    },
    //取件码取件
    putCodeSubmit(evt) {
        let take_code = evt.detail.value.take_code
        this.setData({
            take_code
        })
        this.doOrder({
            currentTarget: {
                dataset: {
                    submittype: this.data.submittype,
                    orderid: this.data.orderid
                }
            }
        })

    },
    //手机号搜索
    showInput() {
        this.setData({
            showInput: !this.data.showInput
        })
    },
    //弹出日期选择
    showDistpicker: function() {
        this.setData({
            showDistpicker: !this.data.showDistpicker
        })
    },
    bindChange: function(e) {
        let val = e.detail.value
        setDate(this.data.years[val[0]], this.data.months[val[1]], 1, this)
    },
    //修改日期确认
    dateConfirm() {
        this.showDistpicker()
        this.onPullDownRefresh()
    },
    // 电话号码搜索
    mobileSearch(evt) {
        this.setData({
            mobile_search: evt.detail.value,
            showFilter: false
        })
        this.onPullDownRefresh()
    },

    //筛选
    isShowFilter() {
        this.setData({
            showFilter: !this.data.showFilter
        })
    },
    reset() {
        this.setData({
            current_village: null
        })
        this.onPullDownRefresh()
        this.isShowFilter()
    },
    chooseVillage(evt) {
        let current_village = evt.currentTarget.dataset.id
        this.setData({
            current_village: current_village
        })
    },
    filter() {
        this.onPullDownRefresh()
        this.isShowFilter()
    },
    onPullDownRefresh: function () {
        let tab = pool.get(this.data.status)
        tab.page = 1
        tab.nextPage = true
        tab.list = []
        this.loadData()
    },
    onReachBottom: function() {
        this.loadData()
    },
})